package com.cheer.job;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.cheer.enums.OaIntegralRuleEnum;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;


/**
 * @author cheer
 */
@Component
@Slf4j
public class OaLearnListener implements ApplicationListener<ApplicationReadyEvent> {

    private static final Logger logger = LoggerFactory.getLogger(OaLearnListener.class);

    protected static DelayQueue<OaLearnTask> delayQueue = new DelayQueue<>();

    protected static ConcurrentHashMap<String, OaLearnTask> learnTaskMap = new ConcurrentHashMap<>();

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        logger.info("OaLearnListener start... 应用程序已完成初始化并已经准备好提供服务");
        new Thread(() -> {
            while (true) {
                logger.info("OaLearnListener start... 监听队列");
                try {
                    logger.info("start take");
                    OaLearnTask task = delayQueue.take();
                    if (learnTaskMap.remove(task.getOpenid(), task)) {
                        logger.debug("OaLearnListener start... 执行任务");
                        task.run();
                    }

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }).start();
    }

    public static void putTask(String openid, OaIntegralRuleEnum integralRuleEnum, Integer itemsId) {
        OaLearnTask learnTask = new OaLearnTask(openid, integralRuleEnum, itemsId);
        delayQueue.put(learnTask);
        learnTaskMap.put(openid, learnTask);
    }

    public static void removeTask(String openid) {
        OaLearnTask task = learnTaskMap.remove(openid);
        if (task == null) {
            return;
        }

        if (DateUtil.between(task.getCreateTime(), new Date(), DateUnit.SECOND) >= 120) {
            task.run();
        }
    }
}